package cn.tworice.common.util;


import com.alibaba.fastjson.JSON;
import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.methods.InputStreamRequestEntity;
import org.apache.commons.httpclient.methods.PostMethod;
import org.apache.commons.httpclient.methods.RequestEntity;

import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.Map;

public class HttpUtil {
    public static String post(String url, Map<String, Object> params) throws IOException {
        HttpClient client = new HttpClient(); // 客户端实例化
        PostMethod postMethod = new PostMethod(url); // 请求方法post，可以将请求路径传入构造参数中
        postMethod.addRequestHeader("Content-type", "application/json; charset=utf-8");

        byte[] requestBytes = JSON.toJSONString(params).getBytes("utf-8"); // 将参数转为二进制流
        InputStream inputStream = new ByteArrayInputStream(requestBytes, 0,
                requestBytes.length);
        RequestEntity requestEntity = new InputStreamRequestEntity(inputStream,
                requestBytes.length, "application/json; charset=utf-8"); // 请求体
        postMethod.setRequestEntity(requestEntity);   // 将参数放入请求体

        client.executeMethod(postMethod);  // 执行方法
        byte[] responseBody = postMethod.getResponseBody(); // 得到相应数据
        return new String(responseBody);
    }

    public static String get(String url) throws IOException {
        StringBuilder response = new StringBuilder();
        HttpURLConnection connection = getHttpURLConnection(url,"GET");
        // 获取响应状态码
        int responseCode = connection.getResponseCode();
        if (responseCode == HttpURLConnection.HTTP_OK) { // 请求成功
            // 读取响应数据
            BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream()));
            String inputLine;

            while ((inputLine = in.readLine()) != null) {
                response.append(inputLine);
            }
            in.close();
            connection.disconnect();
            return response.toString();
        } else {
            connection.disconnect();
            throw new RuntimeException("HTTP request failed: " + responseCode);
        }
    }

    public static boolean isHttp(String url) {
        return !StringUtils.isEmpty(url) && url.startsWith("http:");
    }

    public static boolean isHttps(String url) {
        return !StringUtils.isEmpty(url) && url.startsWith("https:");
    }

    private static HttpURLConnection getHttpURLConnection(String url, String method) throws IOException {
        URL urlObj = new URL(url);
        // 打开连接
        HttpURLConnection connection = (HttpURLConnection) urlObj.openConnection();
        // 设置请求方法为GET
        connection.setRequestMethod(method);
        // 设置连接超时时间
        connection.setConnectTimeout(5000);
        // 设置读取超时时间
        connection.setReadTimeout(5000);
        connection.setRequestProperty("Content-Type", "text/plain; charset=UTF-8");
        connection.setRequestProperty("Origin", "https://tworice.cn");
        // 有反爬机制，不定期更换以下标识
        connection.setRequestProperty("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/121.0.0.0 Safari/537.36 Edg/121.0.0.0");
        // 发送请求
        connection.connect();
        return connection;
    }
}
